<template>
  <div>
      <Row>
        <Col span="12">
          <el-amap-search-box class="search-box" :search-option="searchOption"
                              :on-search-result="onSearchResult"></el-amap-search-box>
        </Col>
        <Col span="12">
          <Button @click="addFence">添加围栏</Button>
          <Button @click="removeFence">清除围栏</Button>
        </Col>
      </Row>
      <Row style="height: 500px">
        <el-amap class="amap-box" vid="map"
                 :zoom="zoom"
                 :center="center"
                 :amap-manager="amapManager"
                 :events="events"
        >
        </el-amap>
      </Row>
  </div>
</template>

<script>
  import VueAMap from 'vue-amap'
  let amapManager = new VueAMap.AMapManager()
  export default {
    name: 'fence-manage',
    data () {
      return {
        amapManager,
        zoom: 12,
        center: [106.5572085, 29.6154994],
        events: {
          init (o) {

          }
        },
        searchOption: {
          city: '重庆',
          citylimit: false
        },
        fenceForm:{
          coordinate:[]
        },
        rectangle:null,
        mouseTool: null,
        overlays: [],
      }
    },
    methods: {
      addFence () {
        let _this = this
        let map = amapManager.getMap()
        if(this.fenceForm.coordinate.length >0){
          this.$Message.warning("围栏已存在!")
          return
        }
        if(this.rectangle){
          map.remove(this.rectangle)
        }
        map.plugin(['AMap.MouseTool'], function () {
          let mouseTool = new AMap.MouseTool(map)
          _this.mouseTool = mouseTool
          //添加事件
          mouseTool.rectangle()
          AMap.event.addListener(mouseTool, 'draw', function (e) {
            _this.fenceForm.coordinate = []
            let path = e.obj.getPath()
            path.forEach(e=>{
             _this.fenceForm.coordinate.push([e.getLng(),e.getLat()])
            })
            mouseTool.close(false)
          })
        })
      },
      removeFence () {
        this.fenceForm.coordinate = []
        if(this.mouseTool){
          this.mouseTool.close(true)
        }
        if(this.rectangle){
          amapManager.getMap().remove(this.rectangle)
        }
      },
      onSearchResult (pois) {
        let latSum = 0
        let lngSum = 0
        if (pois.length > 0) {
          pois.forEach(poi => {
            let { lng, lat } = poi
            lngSum += lng
            latSum += lat
          })
          let center = {
            lng: lngSum / pois.length,
            lat: latSum / pois.length
          }
          this.center = [center.lng, center.lat]
          this.zoom = 15
        }
      }
    },
    mounted () {
      this.init()
    }
  }
</script>


<style scoped>

  div {
    background: #fff;
  }
</style>